// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: xguo

#include "coin2/exchange/binance_futures/api_order/native_rest_async_asio_subscriber.h"

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>

#include "coin2/base/log.h"

namespace coin2::exchange::binance_futures::api_order {

void BinanceFuturesRestAsyncAsioSubscriber::QueryTransfer() {
  int64_t curr_ts = GetCurrentTimestamp();
  if (curr_ts - last_query_transfer_ts_ < 20e9) {
    return;
  }

  auto http_context = rest_client()->QueryTransfer("USDT");
  if (!http_context) return;
  http_context->handler =
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
  last_query_transfer_ts_ = curr_ts;
}

void BinanceFuturesRestAsyncAsioSubscriber::QueryFundingFee() {
  auto http_context = rest_client()->QueryFundingFee();
  if (!http_context) return;
  http_context->handler =
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BinanceFuturesRestAsyncAsioSubscriber::QueryBalanceAndPosition() {
  if (symcache_->IsPortfolioMarginTrading()) {
    QueryCrossMargin();
  }

  RestParams params;
  params.set_recv_window(5000);
  auto http_context = rest_client()->QueryAccountBalanceAndAccountPosition(params);
  if (!http_context) return;
  http_context->handler =
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BinanceFuturesRestAsyncAsioSubscriber::QueryCrossMargin() {
  RestParams params;
  params.set_recv_window(5000);
  auto http_context = rest_client()->QueryCrossMargin(params);
  if (!http_context) return;
  http_context->handler =
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BinanceFuturesRestAsyncAsioSubscriber::QueryOpenOrders(const std::string& native_symbol) {
  RestParams params;
  params.set_symbol(native_symbol);
  params.set_recv_window(5000);
  auto http_context = rest_client()->QueryOpenOrders(params);
  if (!http_context) return;
  http_context->handler =
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BinanceFuturesRestAsyncAsioSubscriber::QueryHistoryOrders(const std::string& native_symbol) {
  RestParams params;
  params.set_symbol(native_symbol);
  params.set_limit(90);
  params.set_recv_window(5000);
  auto http_context = rest_client()->QueryAllOrders(params);
  if (!http_context) return;
  http_context->handler =
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BinanceFuturesRestAsyncAsioSubscriber::QueryFills(const std::string& native_symbol) {
  RestParams params;
  params.set_symbol(native_symbol);
  params.set_limit(200);
  params.set_recv_window(5000);
  auto http_context = rest_client()->QueryTrades(params);
  if (!http_context) return;
  http_context->handler =
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BinanceFuturesRestAsyncAsioSubscriber::GenListenKey(bool is_init) {
  auto http_context = rest_client()->GenListenKey(is_init);
  if (!http_context) return;
  http_context->handler =
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BinanceFuturesRestAsyncAsioSubscriber::SubscribeAsync() {
  LOG(INFO) << "Binance Futures rest subscriber config: " << config_.DebugString();

  AddPeriodicTask(
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::GenListenKey, this, true),
      5,
      "init_gen_listen_key");

  AddPeriodicTask(
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::GenListenKey, this, false),
      300,
      "gen_listen_key",
      300);

  AddPeriodicTask(
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::QueryBalanceAndPosition, this),
      config_.query_account_position_period_sec(),
      "query_balance_and_position");

  AddPeriodicTask(
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::QueryFundingFee, this),
      60 * 5,
      "query_funding_fee");

  const auto symbol_list = native_symbols();

  auto query_open_orders_period_sec = config_.query_open_orders_period_sec();
  if (symbol_list.size() < 40) {
    AddPeriodicTask(
        std::bind(
            &BinanceFuturesRestAsyncAsioSubscriber::QueryOpenOrders,
            this,
            std::placeholders::_1),
        query_open_orders_period_sec,
        "query_open_orders",
        symbol_list);
  } else {
    if (query_open_orders_period_sec < 60) {
      LOG(WARNING) << "query open orders is too frequent as it consumes 40 rate limit per time";
    }
    AddPeriodicTask(
        std::bind(&BinanceFuturesRestAsyncAsioSubscriber::QueryOpenOrders, this, ""),
        query_open_orders_period_sec,
        "query_open_orders");
  }

  AddPeriodicTask(
      std::bind(
          &BinanceFuturesRestAsyncAsioSubscriber::QueryHistoryOrders,
          this,
          std::placeholders::_1),
      std::bind(
          &BinanceFuturesRestAsyncAsioSubscriber::SkipQuery,
          this,
          "query_history_orders",
          std::placeholders::_1),
      config_.query_cancel_orders_period_sec(),
      "query_history_orders",
      symbol_list);

  AddPeriodicTask(
      std::bind(&BinanceFuturesRestAsyncAsioSubscriber::QueryFills, this, std::placeholders::_1),
      std::bind(
          &BinanceFuturesRestAsyncAsioSubscriber::SkipQuery,
          this,
          "query_fills",
          std::placeholders::_1),
      config_.query_fill_period_sec(),
      "query_fills",
      symbol_list);
}

}  // namespace coin2::exchange::binance_futures::api_order
